package com.springIOC.BeanPostProcessor;

import com.springIOC.Interceptro.MyInterceptor1;
import com.springIOC.Pointcut.MyPointCut1;
import com.springIOC.Pointcut.MyPointCutAdvicor;
import com.springIOC.bean.Bean5;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by 41579 on 2017/1/7.
 */
public class MyBeanPostProcessor1 implements BeanPostProcessor{
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
//        Object obj = Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), new MyInvocation(bean));

        ProxyFactory proxyFactory2 = new ProxyFactory(new Bean5());
        proxyFactory2.setProxyTargetClass(true);//加上这行则不报错，因为使用CGLIB方式了
        MyPointCutAdvicor myPointCutAdvicor2 = new MyPointCutAdvicor();
        myPointCutAdvicor2.setAdvice(new MyInterceptor1());
        myPointCutAdvicor2.setPointcut(new MyPointCut1());
        proxyFactory2.addAdvisor(myPointCutAdvicor2);

        return proxyFactory2.getProxy();
    }

    class MyInvocation implements  InvocationHandler{
        Object bean;
        public MyInvocation(Object bean){
            this.bean = bean;
        }
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("before.......");
            Object result = method.invoke(bean,args);
            System.out.println("after....");
            return result;
        }
    }
}
